import { createRouter, createWebHashHistory } from "vue-router";
import { routers } from './routers'
import { ElNotification } from "element-plus";
import { store } from "@/Pstore/store";
import { globalStore } from '@/Pstore/Global'

const router = createRouter({
    history: createWebHashHistory(),
    routes: routers,
})

router.beforeEach(async (to, _, next) => {
    window.scrollTo(0, 0);
    const $store = store()
    const globalStores = globalStore()
    const result = await globalStores.getUserData()
    if (result) {
        if (to.name == 'login' || to.name == 'regist') {
            ElNotification.warning({ title: '如果要进入该页面请尝试退出登录', message: '去试试看吧' })
            next(false)
            return
        }
    } else {
        if (to.name == 'center' || to.name == 'mypaylist' || to.name == 'teamlist' || to.name == 'shopcart' || to.name == 'success') {
            ElNotification.warning({ title: '如果要进入该页面请尝试登录', message: '去试试看吧' })
            next(false)
            return
        }
    }
    if (to.meta.asyncTitel && to.name == 'search') {
        document.title = to.query.searchTitel ? document.title = to.query.searchTitel as string : '搜索'
    } else { document.title = to.meta.titel as string }
    if (to.meta.check) {
        switch (to.name) {
            case 'search':
                if (!$store.itemData || Object.keys($store.itemData).length == 0) {
                    next({ name: 'search' })
                    return
                }
        }
    }
    next()
})

export { router }